Write a function with the name standardize that normalizes the values of a given vector with the following formula:
\[(x - \bar{x}) / S\]
where \(x\) is each input value, \(\bar{x}\) is the sample mean value and \(S\) the sample standard deviation.R’s standard deviation function is sd(). Don’t forget to use the option na.rm = TRUE and be careful when setting the brackets around the formula.
standardize <- function (x) {
(x - mean(x, na.rm = TRUE)) / sd(x, na.rm = TRUE)
}
Please run the following code create a vector with 30 randomly selected values.
vector <- sample(1:100, 30)
standardize() function to see if it works.
standardize(vector)
## [1] -0.16297849 -1.73455681 -0.12805453 1.02443624 0.46565283 0.95458831 1.26890397 0.84981642 1.40859982 1.33875190 -1.42024115 1.23398001
## [13] -0.61699001 0.32595698 1.44352379 -0.02328264 0.57042472 -1.03607756 -1.14084944 -0.19790245 -0.96622963 1.12920812 -1.66470888 -0.47729416
## [25] -0.44237019 -0.37252227 -0.26775038 -0.68683793 0.77996850 -1.45516511
<) to check if a condition is true or false. For printing, you should use the print() function.
if (standardize(vector)[1] < 0) {
print("TRUE")
} else {
print("FALSE")
}
## [1] "TRUE"